<?php
// 应用公共文件

use app\common\service\AuthService;
use think\facade\Db;
use think\facade\Cache;
use think\facade\Validate;
use think\facade\Env;
use think\Url;

if (!function_exists('__url')) {

    /**
     * 构建URL地址
     * @param string $url
     * @param array $vars
     * @param bool $suffix
     * @param bool $domain
     * @return string
     */
    function __url(string $url = '', array $vars = [], $suffix = true, $domain = false)
    {
        return url($url, $vars, $suffix, $domain)->build();
    }
}

if (!function_exists('password')) {

    /**
     * 密码加密算法
     * @param $value 需要加密的值
     * @param $type  加密类型，默认为md5 （md5, hash）
     * @return mixed
     */
    function password($value)
    {
        $value = sha1('laysns_') . md5($value) . md5('_encrypt') . sha1($value);
        return sha1($value);
    }

}

if (!function_exists('xdebug')) {

    /**
     * debug调试
     * @param string|array $data 打印信息
     * @param string $type 类型
     * @param string $suffix 文件后缀名
     * @param bool $force
     * @param null $file
     */
    function xdebug($data, $type = 'xdebug', $suffix = null, $force = false, $file = null)
    {
        !is_dir(runtime_path() . 'xdebug/') && mkdir(runtime_path() . 'xdebug/');
        if (is_null($file)) {
            $file = is_null($suffix) ? runtime_path() . 'xdebug/' . date('Ymd') . '.txt' : runtime_path() . 'xdebug/' . date('Ymd') . "_{$suffix}" . '.txt';
        }
        file_put_contents($file, "[" . date('Y-m-d H:i:s') . "] " . "========================= {$type} ===========================" . PHP_EOL, FILE_APPEND);
        $str = ((is_string($data) ? $data : (is_array($data) || is_object($data))) ? print_r($data, true) : var_export($data, true)) . PHP_EOL;
        $force ? file_put_contents($file, $str) : file_put_contents($file, $str, FILE_APPEND);
    }
}

if (!function_exists('array_format_key')) {
    /**
     * 二位数组重新组合数据
     * @param $array
     * @param $key
     * @return array
     */
    function array_format_key($array, $key)
    {
        $newArray = [];
        foreach ($array as $vo) {
            $newArray[$vo[$key]] = $vo;
        }
        return $newArray;
    }

}

if (!function_exists('auth')) {

    /**
     * auth权限验证
     * @param $node
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function auth($node = null)
    {
        $authService = new AuthService(session('admin.id'));


         $check = $authService->checkNode($node);

        return $check;
    }
}

if (!function_exists('lsql')) {
    function lsql($die = 0)
    {
        echo Db::getLastSql();
        if ($die) {
            die(1);
        }
    }
}

if (!function_exists('php_alert')) {
    function php_alert($msg)
    {
        dd("<script type='text/javascript'>alert('" . $msg . "');</script>");
    }
}

if (!function_exists('list_sort_by')) {
    /**
     * 对查询结果集进行排序
     * @access public
     * @param array $list 查询结果
     * @param string $field 排序的字段名
     * @param array $sortby 排序类型
     * asc正向排序 desc逆向排序 nat自然排序
     * @return array
     */
    function list_sort_by($list, $field, $sortby = 'asc')
    {

        if (is_array($list)) {
            $refer = array();
            $resultSet = array();

            foreach ($list as $i => $data) {
                $refer[$i] = $data[$field];
            }

            switch ($sortby) {
                case 'asc': // 正向排序
                    asort($refer);
                    break;
                case 'desc': // 逆向排序
                    arsort($refer);
                    break;
                case 'nat': // 自然排序
                    natcasesort($refer);
                    break;
            }
            foreach ($refer as $key => $val) {
                $resultSet[] = &$list[$key];
            }

            return $resultSet;
        }
        return false;
    }
}

/**
 * 删除文件夹
 * @param string $dirname 目录
 * @param bool $withself 是否删除自身
 * @return boolean
 */
function rmdirs($dirname, $withself = true)
{
    if (!is_dir($dirname)) {
        return false;
    }
    $files = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::CHILD_FIRST
    );

    foreach ($files as $fileinfo) {
        $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
        $todo($fileinfo->getRealPath());
    }
    if ($withself) {
        @rmdir($dirname);
    }
    return true;
}


if (!function_exists('create_random_str')) {
    /**
     * 随机字符
     * @param number $length 长度
     * @param string $type 类型
     * @param number $convert 转换大小写
     * @return string
     */
    function create_random_str($length = 6, $type = 'all', $convert = 0)
    {
        $config = array(
            'number' => '1234567890',
            'license_plate' => '1234567890ABCDEFGHJKLMNPQRSTUVWXYZ',
            'letter' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
            'string' => 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
            'all' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
        );
        if (!isset($config[$type])) $type = 'string';
        $string = $config[$type];
        $code = '';
        $strlen = strlen($string) - 1;
        for ($i = 0; $i < $length; $i++) {
            $code .= $string[mt_rand(0, $strlen)];
        }
        if (!empty($convert)) {
            $code = ($convert > 0) ? strtoupper($code) : strtolower($code);
        }
        return $code;
    }
}
if (!function_exists('get_url_domain')) {
    function get_url_domain($domain)
    {
        $domain_postfix_cn_array = array("com", "net", "org", "gov", "edu", "com.cn", "cn");
        $array_domain = explode(".", $domain);
        $array_num = count($array_domain) - 1;
        if ($array_domain[$array_num] == 'cn') {
            if (in_array($array_domain[$array_num - 1], $domain_postfix_cn_array)) {
                $re_domain = $array_domain[$array_num - 2] . "." . $array_domain[$array_num - 1] . "." . $array_domain[$array_num];
            } else {
                $re_domain = $array_domain[$array_num - 1] . "." . $array_domain[$array_num];
            }
        } else {
            $re_domain = $array_domain[$array_num - 1] . "." . $array_domain[$array_num];
        }
        return $re_domain;
    }
}
function substr_replace_ext($str, $replacement = '*', $start = 1, $lengthOrEnd = 3)
{
    $len = mb_strlen($str, 'utf-8');
    if($lengthOrEnd<0){
        $str1 = mb_substr($str, 0,$start, 'utf-8');
        $str2 = substr($str, $lengthOrEnd);
        $length=$len+$lengthOrEnd-$start;
    }elseif ($len > intval($start + $lengthOrEnd)) {
        $str1 = mb_substr($str, 0, $start, 'utf-8');
        $str2 = mb_substr($str, intval($start + $lengthOrEnd), NULL, 'utf-8');
        $length=$lengthOrEnd;
    } else {
        $str1 = mb_substr($str, 0, 1, 'utf-8');
        $str2 = mb_substr($str, $len - 1, 1, 'utf-8');
        $length = $len - 2;
    }
    $new_str = $str1;
    for ($i = 0; $i < $length; $i++) {
        $new_str .= $replacement;
    }
    $new_str .= $str2;
    return $new_str;
}
/**
 * 获取第一张图为封面图
 */
if (!function_exists('get_cover_pic')) {
    function get_coverpic($content, $num = 1)
    {
        preg_match_all('/<img[^>]*src=[\'"]?([^>\'"\s]*)[\'"]?[^>]*>/i', htmlspecialchars_decode($content), $match);
        if (count(@$match[1])) {
            if ($num > 1 && count($match[1]) > 1) {
                return array_slice($match[1], 0, $num);
            } else {
                return $match[1][0];
            }

        } else {
            return '';
        }
    }
}

/**
 * 根据文章内容截取描述
 *
 */
if (!function_exists('get_description')) {
    function get_description($content, $count = 128)
    {
        $content = html_entity_decode($content);
        $content = preg_replace("@<script(.*?)</script>@is", "", $content);
        $content = preg_replace("@<iframe(.*?)</iframe>@is", "", $content);
        $content = preg_replace("@<style(.*?)</style>@is", "", $content);
        $content = preg_replace("@<(.*?)>@is", "", $content);
        $content = str_replace(PHP_EOL, '', $content);
        $space = array(" ", "　", "  ", " ", " ");
        $go_away = array("", "", "", "", "");
        $content = str_replace($space, $go_away, $content);
        $res = mb_substr($content, 0, $count, 'UTF-8');
        if (mb_strlen($content, 'UTF-8') > $count) {
            $res = $res . "...";
        }
        return $res;
    }
}


//将html里面的网址补全
function formaturl($html, $domain)
{
    if (preg_match_all("/(<img[^>]+src=\"([^\"]+)\"[^>]*>)|(<a[^>]+href=\"([^\"]+)\"[^>]*>)|(<img[^>]+src='([^']+)'[^>]*>)|(<a[^>]+href='([^']+)'[^>]*>)/i", $html, $regs)) {
        foreach ($regs[2] as $num => $url) {
            if ($url&&strpos($url,'http')===false) {
                $html = str_replace($url, $domain . $url, $html);
            }
        }
    }

    return $html;
}
if (!function_exists('friendlyDate')) {
    function friendlyDate($sTime, $type = 'normal', $alt = 'false')
    {
        if (!$sTime) {
            return '';
        }elseif (!is_numeric($sTime)){
            $sTime=strtotime($sTime);
        }
        //sTime=源时间，cTime=当前时间，dTime=时间差
        $cTime = time();
        $dTime = $cTime - $sTime;
        $dDay = intval(date("z", $cTime)) - intval(date("z", $sTime));
        //$dDay     =   intval($dTime/3600/24);
        $dYear = intval(date("Y", $cTime)) - intval(date("Y", $sTime));
        //normal：n秒前，n分钟前，n小时前，日期
        if ($type == 'normal') {
            if ($dTime < 60) {
                if ($dTime < 10) {
                    return '刚刚'; //by yangjs
                } else {
                    return intval(floor($dTime / 10) * 10) . "秒前";
                }
            } elseif ($dTime < 3600) {
                return intval($dTime / 60) . "分钟前";
                //今天的数据.年份相同.日期相同.
            } elseif ($dYear == 0 && $dDay == 0) {
                //return intval($dTime/3600)."小时前";
                return '今天' . date('H:i', $sTime);
            } elseif ($dYear == 0) {
                return date("m月d日 H:i", $sTime);
            } else {
                return date("Y-m-d", $sTime);
            }
        } elseif ($type == 'mohu') {
            if ($dTime < 60) {
                return $dTime . "秒前";
            } elseif ($dTime < 3600) {
                return intval($dTime / 60) . "分钟前";
            } elseif ($dTime >= 3600 && $dDay == 0) {
                return intval($dTime / 3600) . "小时前";
            } elseif ($dDay > 0 && $dDay <= 7) {
                return intval($dDay) . "天前";
            } elseif ($dDay > 7 && $dDay <= 30) {
                return intval($dDay / 7) . '周前';
            } elseif ($dDay > 30) {
                return intval($dDay / 30) . '个月前';
            }
            //full: Y-m-d , H:i:s
        } elseif ($type == 'full') {
            return date("Y-m-d , H:i:s", $sTime);
        } elseif ($type == 'ymd') {
            return date("Y-m-d", $sTime);
        } else {
            if ($dTime < 60) {
                return $dTime . "秒前";
            } elseif ($dTime < 3600) {
                return intval($dTime / 60) . "分钟前";
            } elseif ($dTime >= 3600 && $dDay == 0) {
                return intval($dTime / 3600) . "小时前";
            } elseif ($dYear == 0) {
                return date("Y-m-d H:i:s", $sTime);
            } else {
                return date("Y-m-d H:i:s", $sTime);
            }
        }
    }
}

/**
 * 判断URI是否可有效访问
 *
 */
function uri_valid($url)
{
    stream_context_set_default(
        array(
            'http' => array(
                'timeout' => 5,
            )
        )
    );
    try {
        $header = get_headers($url, 1);
    }catch (\Exception $e){
        file_put_contents(YEWU_FILE, CUR_DATETIME . '获取资源地址无效：' . $url . PHP_EOL, FILE_APPEND);
        return false;
    }
    if (strpos($header[0], '200')) {
        return true;
    }
    if (strpos($header[0], '404')) {
        return false;
    }
    if (strpos($header[0], '301') || strpos($header[0], '302')) {
        if (is_array($header['Location'])) {
            $redirectUrl = $header['Location'][count($header['Location']) - 1];
        } else {
            $redirectUrl = $header['Location'];
        }
        return uri_valid($redirectUrl);
    }
}

function setSessionInc($key)
{
    if (session($key)) {
        session($key, session($key) + 1);
    } else {
        session($key, 1);
    }
}

function format_bytes($bytes, $unit = "", $decimals = 2) {
    $units = array('B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4, 'PB' => 5, 'EB' => 6, 'ZB' => 7, 'YB' => 8);
    $value = 0;
    if ($bytes > 0) {
        if (!array_key_exists($unit, $units)) {
            $pow = floor(log($bytes)/log(1024));
            $unit = array_search($pow, $units);
        }
        $value = ($bytes/pow(1024,floor($units[$unit])));
    }

    if (!is_numeric($decimals) || $decimals < 0) {
        $decimals = 2;
    }

    return sprintf('%.' . $decimals . 'f '.$unit, $value);
}

function string_htmlspecialchars($string, $flags = null)
{
    if (is_array($string)) {
        foreach ($string as $key => $val) {
            $string[$key] = string_htmlspecialchars($val, $flags);
        }
    } else {
        if ($flags === null) {
            $string = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string);
            if (strpos($string, '&amp;#') !== false) {
                $string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', $string);
            }
        } else {
            if (PHP_VERSION < '5.4.0') {
                $string = htmlspecialchars($string, $flags);
            } else {
                if (!defined('CHARSET') || (strtolower(CHARSET) == 'utf-8')) {
                    $charset = 'UTF-8';
                } else {
                    $charset = 'ISO-8859-1';
                }
                $string = htmlspecialchars($string, $flags, $charset);
            }
        }
    }

    return $string;
}
//去除html标签和空白
function cutstr_html($string){
    $string = strip_tags($string);
    $skipstr = implode('|', ["\t", "\r\n", "\r", "\n", " "]);
    $string = preg_replace(array("/($skipstr)/i"), '.', $string);
    return trim($string);
}
function remove_xss($html)
{
    $html = htmlspecialchars_decode($html);
    preg_match_all("/\<([^\<]+)\>/is", $html, $ms);

    $searchs[] = '<';
    $replaces[] = '&lt;';
    $searchs[] = '>';
    $replaces[] = '&gt;';

    if ($ms[1]) {
        $allowtags = 'iframe|video|attach|img|a|font|div|table|tbody|caption|tr|td|th|br|p|b|strong|i|u|em|span|ol|ul|li|blockquote|strike|pre|code|embed';
        $ms[1] = array_unique($ms[1]);
        foreach ($ms[1] as $value) {
            $searchs[] = "&lt;" . $value . "&gt;";

            $value = str_replace('&amp;', '_uch_tmp_str_', $value);
            $value = string_htmlspecialchars($value);
            $value = str_replace('_uch_tmp_str_', '&amp;', $value);

            $value = str_replace(array('\\', '/*'), array('.', '/.'), $value);
            $skipkeys = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate',
                'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange',
                'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick',
                'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate',
                'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete',
                'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel',
                'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart',
                'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop',
                'onsubmit', 'onunload', 'javascript', 'script', 'eval', 'behaviour', 'expression');
            $skipstr = implode('|', $skipkeys);
            $value = preg_replace(array("/($skipstr)/i"), '.', $value);
            if (!preg_match("/^[\/|\s]?($allowtags)(\s+|$)/is", $value)) {
                $value = '';
            }
            $replaces[] = empty($value) ? '' : "<" . str_replace('&quot;', '"', $value) . ">";
        }
    }
    $html = str_replace($searchs, $replaces, $html);
    $html = htmlspecialchars($html);
    return $html;
}
function validate_ext($only,$rule,$checkCaptcha=0,$otherParm=[],$needPost=1){
    if($needPost&&!request()->isPost()){
        return ['code'=>0,'msg'=>'不是POST请求'];
    }
    $post = request()->only($only);
    if($otherParm){
        $post=array_merge($otherParm,$post);
    }
    if(empty($post)){
        return ['code'=>0,'msg'=>'请求参数不完整'];
    }
    if ($checkCaptcha&&(!isset($post['captcha'])||!captcha_check($post['captcha']))) {
        return array('code' => 0, 'msg' => '图形码未填写或写错', 'data' => []);
    }
    try {
        validate($rule)->check($post);
    }catch (\Exception $e){
        return ['code'=>0,'msg'=>$e->getMessage(),'data'=>[]];
    }
    return $post;
}

//生成无限级树
function buildPidTree($pid, $list, $level = 0)
{
    $newList = [];
    foreach ($list as $vo) {
        if ($vo['pid'] == $pid) {
            $level++;
            foreach ($newList as $v) {
                if ($vo['pid'] == $v['pid'] && isset($v['level'])) {
                    $level = $v['level'];
                    break;
                }
            }
            $vo['level'] = $level;
            if ($level > 1) {
                $repeatString = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                $markString   = str_repeat("{$repeatString}|_{$repeatString}", $level - 1);
                $vo['title']  = $markString . $vo['title'];
            }
            $newList[] = $vo;
            $childList = buildPidTree($vo['id'], $list, $level);
            !empty($childList) && $newList = array_merge($newList, $childList);
        }

    }
    return $newList;
}

function checkIsPhoneOrEmail($object,$typeId=3)
{
    $flag=0;
    $checkReg = '/^1[3-9]{1}[0-9]{9}$/';
    if (Validate::is($object, 'email')) {
        $flag=1;
    }elseif(preg_match($checkReg, $object)&&$typeId>1) {
        $flag=2;
    }
    return $flag;
}

function cacheUserid(){
    $uid='';
    if(session('userid')){
        $uid=session('userid');
    }elseif(cookie('userid')){
        $uid=cookie('userid');
        session('userid',$uid);
    }
    return $uid;
}

function cacheUser($shishi = 0)
{
    $userInfo = null;
    $uid = cacheUserid();
    $cacheName = 'user_' . $uid;
    try {
        if ($shishi == 0 && $uid && Cache::has($cacheName)) {
            $userInfo = Cache::get($cacheName);
        } elseif ($uid) {
            $userInfo = Db::name('user')->alias('a')
                ->LeftJoin('user_attribute b', 'a.id=b.user_id')
                ->where('a.id', $uid)
                ->find();
            if ($userInfo) {
                Cache::set($cacheName, $userInfo);
            } else {
                session('userid', null);
                cookie('userid', null);
            }
        }
    } catch (\Exception $e) {
        return null;
    }
    return $userInfo;
}
function dir_create($path, $mode = 0777)
{
    if (is_dir($path)) {
        return true;
    }
    $path = str_replace("\\", '/', $path); //转换路径
    $temp = explode('/', $path);
    $cur_dir = '';
    $max = count($temp) - 1;
    for ($i = 0; $i < $max; $i++) {
        $cur_dir .= $temp[$i] . '/';
        if (@is_dir($cur_dir)) {
            continue;
        }
        @mkdir($cur_dir, 0777, true);
        @chmod($cur_dir, 0777);
    }
    return is_dir($path);
}

function dir_action($source_dir, $action_dir, $del = false)
{
    if (is_dir($source_dir)) {
        $dir = opendir($source_dir);
        if (!is_dir($action_dir)) mkdir($action_dir);
        while (($file = readdir($dir)) !== false) {
            if (($file != '.') && ($file != '..')) {
                if (is_dir($source_dir . '/' . $file)) {
                    dir_action($source_dir . '/' . $file, $action_dir . '/' . $file, $del);
                } else {
                    if ($del) {
                        unlink($action_dir . '/' . $file);
                    } else {
                        if(strpos($file,'.ini')!==false){
                            continue;
                        }else{
                            copy($source_dir . '/' . $file, $action_dir . '/' . $file);
                        }
                    }
                }
            }
        }
        closedir($dir);
    }
}

function file_unzip($zipfile, $savepath)
{
    $archive = new \org\PclZip($zipfile);
    if ($archive->extract(PCLZIP_OPT_PATH, $savepath)) {
        return true;
    }
}

function importsql($lines,$prefix='laysns_')
{
    if (is_file($lines)) {
        $lines = file($lines);
    }elseif (!is_array($lines)){
        $lines=explode('\n',$lines);
    }
    $templine = '';
    foreach ($lines as $line) {
        if (substr($line, 0, 2) == '--' || $line == '' || substr($line, 0, 2) == '/*') {
            continue;
        }
        $templine .= $line;
        if (substr(trim($line), -1, 1) == ';') {
            // 不区分大小写替换前缀

            $templine = str_ireplace($prefix, env('database.prefix','laysns_'), $templine);
            // 忽略数据库中已经存在的数据
            $templine = str_ireplace('INSERT INTO ', 'INSERT IGNORE INTO ', $templine);
            try {
                Db::execute($templine);
            } catch (\PDOException $e) {
                //$e->getMessage();
            }
            $templine = '';
        }
    }
    return true;
}
//查询目录下的文件夹名
function get_subdirs($dir)
{
    $subdirs = array();
    if (!$handle = @opendir($dir)) {
        return $subdirs;
    }
    while ($file = @readdir($handle)) {
        if ($file == '.' || $file == '..' || strpos($file, '.') !== false) {
            continue;
        }
        $subdirs[] = $file;
    }
    return $subdirs;
}
function todayTime($addDay=0){
    $dayTime=strtotime(date('Y-m-d'));
    if($addDay!=0){
       $dayTime=$dayTime+3600*24*$addDay;
    }
    return $dayTime;
}
function show_msg($msg, $class = '')
{
//    ob_flush();
    echo "$msg<br/>";
    flush();
}
function convertUrlQuery($query)
{
    $queryParts = explode('&', $query);
    $params = array();
    foreach ($queryParts as $param) {
        $item = explode('=', $param);
        $params[$item[0]] = $item[1];
    }
    return $params;
}
/**
 * 将参数变为字符串
 * @param $array_query
 * @return string string 'm=content&c=index&a=lists&catid=6&area=0&author=0&h=0&region=0&s=1&page=1' (length=73)
 */
function getUrlQuery($array_query)
{
    $tmp = array();
    foreach($array_query as $k=>$param)
    {
        $tmp[] = $k.'='.$param;
    }
    $params = implode('&',$tmp);
    return $params;
}

function setEnv($name,$value){
    Env::offsetSet($name,$value);
    $envPath = root_path() . DIRECTORY_SEPARATOR . '.env';
    $envinidata=Env::get();
    $inicontent=arr_trinsform_ini($envinidata);
    $fp = fopen($envPath, "w") or die("Couldn't open $envPath");
    fputs($fp,$inicontent);
    fclose($fp);
}

/**
 * author:leishaofa
 * date:20191225
 * effect:ini数据组装
 */
function arr_trinsform_ini(array $a, array $parent = array())
{
    $out = '' . PHP_EOL;
    $keysindent = [];
    foreach ($a as $k => $v) {
        if (is_array($v)) {
            $sec = array_merge((array)$parent, (array)$k);
            $out .= '[' . join('.', $sec) . ']' . PHP_EOL;
            $out .= arr_trinsform_ini($v, $sec);
        } else {
            $key = explode('_', $k);
            if (count($key) > 1 && !in_array($key[0], $keysindent)) {
                $keysindent[] = $key[0];
                $out .= PHP_EOL . PHP_EOL;
                $out .= "[$key[0]]" . PHP_EOL;
                unset($key[0]);
                $out .= implode('_', $key) . " = $v" . PHP_EOL;
                //unset($key);
            } elseif (count($key) > 1 && in_array($key[0], $keysindent)) {
                unset($key[0]);
                $out .= implode('_', $key) . " = $v" . PHP_EOL;
            } else {
                $out .= "$k = $v" . PHP_EOL;
            }
        }
    }
    return $out;
}
//根据ID查询任意表的单行数据或者单个字段
function laysns_id_item($table,$id,$name='')
{
    $return = Db::name($table)->where('id',$id)->find();
    if ($return&&$name&&isset($return[$name])){
        $return=$return[$name];
    }
    return $return;
}

//根据条件查询任意表的多行数据
function laysns_map_items($table,$where,$limit=10,$order=['id'=>'desc'])
{
//    $map条件 https://www.kancloud.cn/manual/thinkphp6_0/1037539
//    [
//        'name'	=>	'thinkphp',
//        'status'=>	1
//    ]
//    [
//        ['name','=','thinkphp'],
//        ['status','=',1]
//    ]
    $items=Db::name($table)->where($where)->order($order)->limit($limit)->select()->toArray();
    if($limit==1&&count($items)){
        $items=$items[0];
    }
    return  $items;
}


/* 获取顶级父类id
 * @param  [type] $id [description]
 * @return [type]     [description]
 */
function get_top_pid($id,$table='article_category')
{
    $r = Db::name($table)->where('id',$id)->field('id,pid')->find();
    if ($r['pid'] != '0') return get_top_pid($r['pid'],$table);
    return $r['id'];
}

/**
 * @param string $table
 * @param null $status
 * @return int
 */
function x_count($table='article',$status=null)
{
    $where=[];
    if($status){
        $where['status']=$status;
    }
    return Db::name($table)->where($where)->count();
}

/**
 * +----------------------------------------------------------
 * 获取当前分类下所有子分类
 * +----------------------------------------------------------
 * $table 数据表名
 * $parent_id 父类ID
 * $child 子类ID临时存储器
 * +----------------------------------------------------------
 */
function ls_child_id($list, $parent_id = '0', &$child_id = '') {

    foreach ((array) $list as $value) {
        if ($value['pid'] == $parent_id) {
            $child_id .= ',' . $value['id'];
            ls_child_id($list, $value['id'], $child_id);
        }
    }

    return $child_id;
}
if (!function_exists('success')) {
    function success($msg,$data=[],$json=1){
        $result = ['code' => 1, 'msg' => $msg, 'data' => $data];
        if ($json) {
            $result = json($result);
        }
        return $result;
    }
}

if (!function_exists('fail')) {
    function fail($msg,$data=[],$json=1)
    {
        $result = ['code' => 0, 'msg' => $msg, 'data' => $data];
        if ($json) {
            $result = json($result);
        }
        return $result;
    }
}